import re

from PageObjectRequests import base_url
from util import http_utils
from util.DataQuery.hzflowOperation import hzflowOperation
from util.g import g
from util.inform.sendEmail import sendEmail
from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.DbTools import DbTools
from util.DataQuery.FormDataDecorator import FormDataDecorator
# from PageObject.write_optcond import WriteOptcond
from PageObjectRequests.write_optcond import WriteOptcond


class WriteMaincaseForm():

    form_btn_loc = (By.LINK_TEXT, '主要情况表')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")

    # 写代码时方便提示, 基本方法完成后删除
    # driver = driver
    def __init__(self, driver=None):
        self.driver = driver
    @property
    def class_name(self):
        return self.__class__.__name__

    @FormDataDecorator
    def main(self, tech_fieldname='', tech_fieldlist="", inchina_spend=None, basic_spend=None,
             mat_ai=None, is_events=None):
        try:
            # BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
            ele = BM.get_ele(driver=self.driver, ele_loc=self.form_btn_loc, time=6)
            detail_url = ele.get_attribute("href")
            if not g.all_optimized:
                BM.switch_to_frame(driver=self.driver, ele_loc=self.content_iframe_loc)
            detail_url = detail_url if detail_url.startswith("https://") else \
                base_url + (detail_url if detail_url.startswith("/") else "/" + detail_url)
            BM.get_cookie(driver=self.driver)
            res = http_utils.send_get(detail_url, driver=self.driver)
            text = res.get("text")
            token = res.get("token")
            self.token = token
            url = "https://gqqy.chinatorch.org.cn/xonlinereport/inforeport/DataInnocom/saveOrUpdateDataEntServdept.do"
            data = {
                "struts.token.name": "token",
                "token": token,
            }

            # 获取技术领域
            domain_dict = hzflowOperation.get_domain_by_namelist(hitech_field_namelist=tech_fieldname)
            data["dataEntServdept.eprZyywssjsly1"] = domain_dict.get("domain1")
            data["dataEntServdept.eprZyywssjsly2"] = domain_dict.get("domain2")
            data["dataEntServdept.eprZyywssjsly3"] = domain_dict.get("domain3")

            # 自动计算或页面参数
            dataEntServdept_id_pattern = '.*?"dataEntServdept.id".value="(.*?)".*?'
            dataEntServdept_id_res = re.findall(dataEntServdept_id_pattern, text, re.S)
            data["dataEntServdept.id"] = "".join(dataEntServdept_id_res)
            dataInnocom_id_pattern = '.*?"dataInnocom.id".value="(.*?)".*?'
            dataInnocom_id_res = re.findall(dataInnocom_id_pattern, text, re.S)
            data["dataInnocom.id"] = "".join(dataInnocom_id_res)
            dataEntServdept_dataId_pattern = '.*?"dataEntServdept.dataId".value="(.*?)".*?'
            dataEntServdept_dataId_res = re.findall(dataEntServdept_dataId_pattern, text, re.S)
            data["dataEntServdept.dataId"] = "".join(dataEntServdept_dataId_res)
            dataEntServdept_entId_pattern = '.*?"dataEntServdept.entId".value="(.*?)".*?'
            dataEntServdept_entId_res = re.findall(dataEntServdept_entId_pattern, text, re.S)
            data["dataEntServdept.entId"] = "".join(dataEntServdept_entId_res)
            dataEntServdept_createDate_pattern = '.*?"dataEntServdept.createDate".value="(.*?)".*?'
            dataEntServdept_createDate_res = re.findall(dataEntServdept_createDate_pattern, text, re.S)
            data["dataEntServdept.createDate"] = "".join(dataEntServdept_createDate_res)

            # 知识产权 一类 二类
            dataEntServdept_eprZscqyl_pattern = '.*?"dataEntServdept.eprZscqyl".*?value="(.*?)".*?'
            dataEntServdept_eprZscqyl_res = re.findall(dataEntServdept_eprZscqyl_pattern, text, re.S)
            data["dataEntServdept.eprZscqyl"] = "".join(dataEntServdept_eprZscqyl_res)
            dataEntServdept_eprZscqel_pattern = '.*?"dataEntServdept.eprZscqel".*?value="(.*?)".*?'
            dataEntServdept_eprZscqel_res = re.findall(dataEntServdept_eprZscqel_pattern, text, re.S)
            data["dataEntServdept.eprZscqel"] = "".join(dataEntServdept_eprZscqel_res)

            # 人力资源情况
            dataEntServdept_eprZgzs_pattern = '.*?"dataEntServdept.eprZgzs".*?value="(.*?)".*?'
            dataEntServdept_eprZgzs_res = re.findall(dataEntServdept_eprZgzs_pattern, text, re.S)
            data["dataEntServdept.eprZgzs"] = "".join(dataEntServdept_eprZgzs_res)
            dataEntServdept_eprCsyjrs_pattern = '.*?"dataEntServdept.eprCsyjrs".*?value="(.*?)".*?'
            dataEntServdept_eprCsyjrs_res = re.findall(dataEntServdept_eprCsyjrs_pattern, text, re.S)
            data["dataEntServdept.eprCsyjrs"] = "".join(dataEntServdept_eprCsyjrs_res)

            # 近三年研究开发费用总额
            dataEntServdept_eprJnyjkffyze_pattern = """.*?"dataEntServdept.eprJnyjkffyze".*?value=['|"](.*?)['|"]"""
            dataEntServdept_eprJnyjkffyze_res = re.findall(dataEntServdept_eprJnyjkffyze_pattern, text, re.S)
            data["dataEntServdept.eprJnyjkffyze"] = "".join(dataEntServdept_eprJnyjkffyze_res)

            # 近一年高新技术产品（服务）收入
            dataEntServdept_eprJngxjscpsr_pattern = """.*?"dataEntServdept.eprJngxjscpsr".*?value=['|"](.*?)['|"]"""
            dataEntServdept_eprJngxjscpsr_res = re.findall(dataEntServdept_eprJngxjscpsr_pattern, text, re.S)
            data["dataEntServdept.eprJngxjscpsr"] = "".join(dataEntServdept_eprJngxjscpsr_res)

            # 近三年经营情况
            #  调用数据查询模块之后这里 一般会有三条数据，需要使用 for 循环。
            optconds = WriteOptcond(driver=self.driver).write_optcond()
            _ = {"category": '', "net_assets": '', "net_revenues": '', "net_income": ''}
            for item in optconds:
                if item.get("category") == "3":
                    data["dataEntServdept.Pjzc3"] = item.get("net_assets")
                    data["dataEntServdept.Pxssr3"] = item.get("net_revenues")
                    data["dataEntServdept.Plr3"] = item.get("net_income")
                if item.get("category") == "2":
                    data["dataEntServdept.Pjzc2"] = item.get("net_assets")
                    data["dataEntServdept.Pxssr2"] = item.get("net_revenues")
                    data["dataEntServdept.Plr2"] = item.get("net_income")
                if item.get("category") == "1":
                    data["dataEntServdept.Pjzc1"] = item.get("net_assets")
                    data["dataEntServdept.Pxssr1"] = item.get("net_revenues")
                    data["dataEntServdept.Plr1"] = item.get("net_income")

            data["dataEntServdept.eprZzgjnfy"] = inchina_spend
            data["dataEntServdept.eprJcyjtr"] = basic_spend
            data["dataEntServdept.eprJnryzsr"] = mat_ai
            data["dataEntServdept.sfwfStatus"] = is_events if is_events in [0, 1] else 0

            result = http_utils.send_post(url, data=data, driver=self.driver)
            text = result.get("text")
            message = result.get("message")
            g.logger.info("主要情况表上传结果: {}".format(message))
            token = result.get("token")
            self.token = token

            if u"成功" in message:
                return True
            else:
                content = "{}-{}---{}--{}".format(g.entname, g.co_id, "主要情况表", message)
                a = sendEmail(subject="autoflow", content=content, target="18235693860@163.com")
                a.send_mail()
                return False
        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(
                err, err.__traceback__.tb_frame.f_globals["__file__"],
                err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)
